package com.mangguo.tingjian.user.controller;


import com.mangguo.tingjian.common.Result;
import com.mangguo.tingjian.user.dto.CountResult;
import com.mangguo.tingjian.user.service.IDwUserRegisterMiniService;
import com.mangguo.tingjian.util.CvsUtils;
import com.mangguo.tingjian.util.DateUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 注册用户-小程序 前端控制器
 * </p>
 *
 * @author auto
 * @since 2019-11-25
 */
@RestController
@RequestMapping("/user/dw-user-register-mini")
@AllArgsConstructor
public class DwUserRegisterMiniController {
    private final IDwUserRegisterMiniService dwUserRegisterMiniService;

    /**
     * 注册用户数按月份统计
     * @return
     */
    @GetMapping("/unique-imei/month")
    public Result<List<CountResult>> appUserCountByMonth(){
        return Result.success(dwUserRegisterMiniService.countUniqueImeiByMonth());
    }

    /**
     * 新增激活用户数按日统计（14天）
     * @return
     */
    @GetMapping("/unique-imei/date")
    public Result<List<CountResult>> userCountByDate(){
        Integer end = DateUtils.getTodayInt();
        Integer start = DateUtils.addDay(end, -14);
        Map<Integer, CountResult> map = new HashMap<>();
        DateUtils.getBetweenDates(start, end).forEach(date -> {
            CountResult countResult = new CountResult();
            countResult.setMDate(date);
            countResult.setCount(0L);
            map.put(date, countResult);
        });
        dwUserRegisterMiniService.countUniqueImeiByDate(start, end).forEach(countResult -> {
            map.get(countResult.getMDate()).setCount(countResult.getCount());
        });
        List<CountResult> results = new ArrayList<>();
        DateUtils.getBetweenDates(start, end).forEach(date -> {
            results.add(map.get(date));
        });
        return Result.success(results);
    }

    /**
     *  注册用户数按月份统计
     * @return
     */
    @GetMapping("/unique-imei/month/download")
    public void userCountByMonthDownload(HttpServletResponse response){
        List<CountResult> countResults = dwUserRegisterMiniService.countUniqueImeiByMonth();
        List<List<String>> list = new ArrayList<>();
        list.add(Arrays.asList("日期", "人数"));
        for(CountResult countResult : countResults){
            list.add(Arrays.asList(countResult.getMYear() + "-" + countResult.getMMonth(), countResult.getCount().toString()));
        }
        CvsUtils.downloadCvs(response, "小程序注册用户月份统计", list);
    }

}
